package com.xtwroot.android.photogallery;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/********************************************************************************
 * using for: 实例化生成新建布局并引用 RecyclerView 视图
 * 丁酉鸡年正月 2017/02/21 20:36
 * @author 西唐王, xtwyzh@gmail.com,xtwroot.com
 * xtwroot Copyrights (c) 2017. All rights reserved.
 ********************************************************************************/
public class PhotoGalleryFragment extends VisibleFragment
{
    private RecyclerView mPhotoRecyclerView;

    private static final String TAG = "PhotoGalleryFragment";
    private List<GalleryItem> mItems = new ArrayList<>();
    private ThumbnailDownloder<PhotoHolder> mThumbnailDownloder;


    public static PhotoGalleryFragment newInstance()
    {
        return new PhotoGalleryFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);
        updateItems();


        Handler responseHandler = new Handler();
        mThumbnailDownloder = new ThumbnailDownloder<>(responseHandler);
        mThumbnailDownloder.setThumbnailDownloadListener(
                new ThumbnailDownloder.ThumbnailDownloadListener<PhotoHolder>()
                {

                    @Override
                    public void onThumbnailDownloaded(PhotoHolder target, Bitmap thumbnail) {
                        Drawable drawable = new BitmapDrawable(getResources(),thumbnail);
                        target.bindDrawable(drawable);
                    }
                }
                );
        mThumbnailDownloder.start();
        mThumbnailDownloder.getLooper();
        Log.i(TAG,"Background thread started");

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mThumbnailDownloder.clearQueue();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_photo_gallery,container,false);

        mPhotoRecyclerView = (RecyclerView)v.findViewById(R.id.fragment_photo_gallery_recycler_view);
        mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));

        mPhotoRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //setupAdapter();
            }
        });

        //设置Item增加、移除动画
        mPhotoRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        mPhotoRecyclerView.addItemDecoration(new DividerItemDecoration(
                getActivity(), DividerItemDecoration.HORIZONTAL));

        setupAdapter();

        return v;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.menu_item_clear:
                QueryPreferences.setStoredQuery(getActivity(),null);
                updateItems();
                return true;
            case R.id.menu_toggle_polling:
                boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity());
                PollService.setServiceAlarm(getActivity(),shouldStartAlarm);
                getActivity().invalidateOptionsMenu();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater)
    {
        super.onCreateOptionsMenu(menu,menuInflater);
        menuInflater.inflate(R.menu.fragment_photo_gallery,menu);

        MenuItem searchItem = menu.findItem(R.id.menu_item_search);
        final SearchView searchView = (SearchView)searchItem.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d(TAG,"QueryTextSubmit: " + query);
                QueryPreferences.setStoredQuery(getActivity(),query);
                updateItems();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d(TAG,"QueryTextChange: " + newText);
                return false;
            }
        });

        MenuItem toggleItem = menu.findItem(R.id.menu_toggle_polling);
        if(PollService.isServiceAlarmOn(getActivity()))
            toggleItem.setTitle(R.string.stop_polling);
        else
            toggleItem.setTitle(R.string.start_polling);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mThumbnailDownloder.quit();
        Log.i(TAG,"Background thread destroyed");
    }

    private void updateItems(){
        String query = QueryPreferences.getSoredQuery(getActivity());
        new FetchItemsTask(query).execute();
    }

    private class FetchItemsTask extends AsyncTask<Void,Void,List<GalleryItem>>
    {
        private String mQuery;
        public FetchItemsTask(String query)
        {
            mQuery = query;
        }

        @Override
        protected List<GalleryItem> doInBackground(Void... params)
        {
            if(mQuery == null)
                return new FlickrFetchr().fetchPhotos();
            else
                return new FlickrFetchr().searchPhotos(mQuery);
        }

        @Override
        protected void onPostExecute(List<GalleryItem> galleryItems) {
            mItems = galleryItems;
            setupAdapter();
        }
    }

    private class PhotoHolder extends RecyclerView.ViewHolder implements View.OnClickListener

    {
        private ImageView mItemImageView;
        private GalleryItem mGalleryItem;

        public PhotoHolder(View itemView)
        {
            super(itemView);
            mItemImageView = (ImageView)itemView.findViewById(R.id.fragment_photo_gallery_image_view);
            itemView.setOnClickListener(this);

        }

        public void bindDrawable(final Drawable drawable)
        {
            mItemImageView.setImageDrawable(drawable);


        }


        private void bindGalleryItem(final GalleryItem galleryItem) throws IOException {

            mGalleryItem = galleryItem;

            Picasso.with(getActivity())
                    .load(galleryItem.getUrl())
                    .placeholder(R.mipmap.ic_launcher)
                    .into(mItemImageView);
            /*
            mItemImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    byte[] bitmapBytes = new byte[0];
                    try {
                        bitmapBytes = new FlickrFetchr().getUrlBytes(galleryItem.getUrl());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    final Bitmap bitmap = BitmapFactory
                            .decodeByteArray(bitmapBytes,0,bitmapBytes.length);
                    Toast t = new Toast(getContext());
                    ImageView imageView = new ImageView(getContext());
                    imageView.setImageBitmap(bitmap);
                    t.setView(imageView);
                    t.setDuration(Toast.LENGTH_SHORT);
                    t.setGravity(Gravity.CENTER,0,0);
                    t.show();
                }
            });
            */
        }

        @Override
        public void onClick(View v) {
            Intent i = PhotoPageActivity.newIntent(getActivity(),mGalleryItem.getOwner());
            startActivity(i);
        }
    }

    private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder>
    {

        private List<GalleryItem> mGalleryItems;

        public void AddGalleryItem(List<GalleryItem> items)
        {
            mGalleryItems.addAll(items);
        }

        public PhotoAdapter(List<GalleryItem> galleryItems)
        {
            mGalleryItems = galleryItems;
        }

        @Override
        public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View view = inflater.inflate(R.layout.gallery_item,parent,false);
            return new PhotoHolder(view);
        }

        @Override
        public void onBindViewHolder(PhotoHolder holder, int position)
        {

            GalleryItem galleryItem = mGalleryItems.get(position);
            /*
            Drawable placeholder = getResources().getDrawable(R.mipmap.ic_launcher);
            holder.bindDrawable(placeholder);
            mThumbnailDownloder.queueThumbnail(holder,galleryItem.getUrl());
            */
            try {
                holder.bindGalleryItem(galleryItem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount()
        {
            return mGalleryItems.size();
        }

    }

    private void setupAdapter()
    {
        if(isAdded())
        {
            mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
        }
    }
}
